package com.qsw.paper.controller.user;


import com.qsw.paper.constant.JwtClaimsConstant;
import com.qsw.paper.constant.MessageConstants;
import com.qsw.paper.pojo.dto.*;
import com.qsw.paper.pojo.entity.Users;
import com.qsw.paper.pojo.vo.UserLoginVO;
import com.qsw.paper.properties.JwtProperties;
import com.qsw.paper.result.Result;
import com.qsw.paper.service.IUsersService;
import com.qsw.paper.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author qsw
 * @since 2024-11-16
 */
@RestController("userUsersController")
@RequestMapping("/user/users")
@RequiredArgsConstructor
@Slf4j
public class UsersController {

    private final IUsersService usersService;
    private final JwtProperties jwtProperties;


    /**
     * 用户登录
     *
     * @param loginDto dto
     * @return token
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody @Validated UserLoginDto loginDto) {
        log.info("用户登录:{}", loginDto);
        Users user = usersService.login(loginDto);
        Map<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID, user.getUserId());
        String token = JwtUtil.createJwt(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setRole(user.getRole());
        userLoginVO.setToken(token);
        return Result.success(userLoginVO, MessageConstants.LOGIN_SUCCESS);
    }


    /**
     * 用户修改个人信息
     *
     * @param userDto dto
     * @return 提示
     */
    @PutMapping("/update")
    public Result<?> update(@RequestBody @Validated UserUpdateDto userDto) {
        log.info("用户修改个人信息:{}", userDto);
        usersService.updateById(userDto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }


    /**
     * 用户修改密码
     *
     * @param paDto dto
     * @return 提示
     */
    @PutMapping("/changePa")
    public Result<?> changePassword(@RequestBody @Validated UserChangPaDto paDto) {
        log.info("用户修改密码:{}", paDto);
        usersService.updatePassword(paDto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }


    /**
     * 获取用户信息
     * @return 用户实体
     */
    @GetMapping("/info")
    public Result<?> getUserDetailById() {
        log.info("用户查询详细信息");
        return Result.success(usersService.getUserDetailById(), MessageConstants.SELECT_OK);
    }


}
